import axios from 'axios'
import router from '../router'
import { Message } from 'element-ui'
import { getUser, removeUser } from '@/utils/storage'
import nprogress from 'nprogress'

const proPath = 'http://yizuxuan.cn:80/api' //'http://8.137.38.55:80/api'
const devPath = 'http://localhost:8001/api'
// 定义后台访问路径
const BASE_URL = proPath

// create an axios instance
const API = axios.create({
	baseURL: BASE_URL, // url = base url
	timeout: 60000 // request timeout
})
// request 拦截器
// 可以自请求发送前对请求做一些处理
// 比如统一加token，对请求参数统一加密
API.interceptors.request.use(
	(config) => {
		config.headers['Content-Type'] = 'application/json;charset=utf-8'
		let user = getUser()
		config.headers['Authorization'] = user ? user.token : ''
		nprogress.start()
		return config
	},
	(error) => {
		return Promise.reject(error)
	}
)

// response 拦截器
// 可以在接口响应后统一处理结果
API.interceptors.response.use(
	(response) => {
		nprogress.done()
		let res = response.data
		// 如果是返回的文件
		if (response.config.responseType === 'blob') {
			return res
		}
		// 兼容服务端返回的字符串数据
		if (typeof res === 'string') {
			res = res ? JSON.parse(res) : res
		}
		if (res.code !== '0') {
			if (res.msg === '' || res.msg === null || res.msg === undefined)
				res.msg === '未知异常'
			Message.error(res.msg)
		}
		return res
	},
	(err) => {
		if (err && err.response) {
			switch (err.response.status) {
				case 400:
					err.message = '请求错误'
					break
				case 401:
					err.message = '未授权，请登录'
					Message.closeAll()
					Message({
						type: 'error',
						message: '登录凭证过期，请重新登录'
					})
					// 清除缓存
					removeUser()
					if (!router.currentRoute.path.includes('/login'))
						router.replace({ path: '/login' })
					break
				case 403:
					err.message = '拒绝访问'
					break
				case 404:
					err.message = `请求地址出错: ${err.response.config.url}`
					break
				case 408:
					err.message = '请求超时'
					break
				case 500:
					err.message = '服务器内部错误'
					break
				case 501:
					err.message = '服务未实现'
					break
				case 502:
					err.message = '网关错误'
					break
				case 503:
					err.message = '服务不可用'
					break
				case 504:
					err.message = '网关超时'
					break
				case 505:
					err.message = 'HTTP版本不受支持'
					break
				default:
			}
		}
		nprogress.done()
		console.error(err)
		// return Promise.reject(err) // 返回接口返回的错误信息
	}
)

export default API
